package com.outbound;

import com.util.MyUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;

public class ProtocolCompleteOutboundHandler extends ChannelOutboundHandlerAdapter{
    private final static byte[] HEADER = new byte[]{(byte)0x7F, (byte)0xF7};
    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception{
        ByteBuf in = (ByteBuf)msg;
        if(in.getByte(in.readerIndex()) != HEADER[0]|| in.getByte(in.readerIndex() + 1) != HEADER[1]) // 如果已经是完整的包，则跳过封包（心跳帧存在此种情况）
            in = completeProtocol(in);

        // TODO: test
        MyUtil.printMsg("Server Sended", in);

        //ctx.writeAndFlush(in);
        ctx.writeAndFlush(in).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()){
                    future.cause().printStackTrace();
                }
            }
        });
    }

    /**
     * 增加帧头(2)，长度(1)和异或校验(1)
     * @param dataFrame
     * @return
     */
    private ByteBuf completeProtocol(ByteBuf dataFrame){

        ByteBuf in = Unpooled.buffer(dataFrame.readableBytes() + HEADER.length + 2);
        in.writeBytes(HEADER);
        if (dataFrame.readableBytes() > 255) // 升级程序包过长则置长度字节为0
            in.writeByte(0x00);
        else
            in.writeByte((byte)(dataFrame.readableBytes() + 1));
        in.writeBytes(dataFrame);
        in.writeByte(MyUtil.xorResult(in));
        return in;
    }
}
